# -*- coding: utf-8 -*-

import cgi
import sys, os
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import facebook
from facebook import FacebookError

FACEBOOK_API_KEY ='a8dfbf5416044ed379eaf8a4bb424fdf'

FACEBOOK_SECRET_KEY ='e950aa7805c18e5fa6223367810a5e3d'

_DEBUG = True
class Utility(webapp.RequestHandler):
    def get(self):
        self.response.out.write(template.render('Utility.js',0))

class FBjqRY(webapp.RequestHandler):
    def get(self):
        self.response.out.write(template.render('FBjqRY.min.js',0))

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write('work')
    def post(self):
        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        #self.response.out.write('work')
        self.response.out.write(template.render('sendMsg.html',0))
        
        

class SendMsg(webapp.RequestHandler):
    def post(self):
        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        msg = self.request.get('msg')
        try:
            ans=fb.admin.getAllocation('notifications_per_day')

            fb.status.set(msg)
            
            self.response.out.write('write %s %s' % (msg, ans))
        except:
            self.response.out.write('error')


def main():
    application = webapp.WSGIApplication([
        ('/',MainPage),
        ('/Utility.js', Utility),
        ('/FBjqRY.min.js', FBjqRY),
        ('/sendMsg',SendMsg)
        ],debug=_DEBUG)
    wsgiref.handlers.CGIHandler().run(application)
    
if __name__ == "__main__":
    main()

       
